<!--
 * @Description:
 * @Author: 月间
 * @Date: 2024-11-25 20:54:29
 * @LastEditTime: 2025-03-30 17:22:17
 * @LastEditors:
-->
<script setup lang="tsx">
import { ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NSwitch } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { fetchDeleteTask, fetchGetTaskList, fetchUpdateTaskStatus } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import TaskOperateDrawer, { type OperateType } from './modules/task-operate-drawer.vue';
const appStore = useAppStore();
const { bool: visible, setTrue: openModal } = useBoolean();

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetTaskList,
  apiParams: {
    current: 1,
    size: 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'id',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'name',
      title: '名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'group',
      title: '分组',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'jobClass',
      title: '任务执行实体类',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'jobParams',
      title: '参数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'execStrategy',
      title: '执行策略',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'expression',
      title: '执行表达式',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'startDatetime',
      title: '任务开始时间',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'endDatetime',
      title: '任务结束时间',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'remark',
      title: '描述',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'isActive',
      title: '状态',
      align: 'center',
      minWidth: 120,
      render(row) {
        if (row.isActive === null) {
          return null;
        }

        return (
          <NSwitch value={row.isActive} round={false} onUpdateValue={value => handleStatusChange(row)}>
            {{
              checked: '开启',
              unchecked: '关闭'
            }}
          </NSwitch>
        );
      }
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      minWidth: 50,
      render(row) {
        return (
          <div class="flex-center gap-8px">
            <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
              {$t('common.edit')}
            </NButton>
          </div>
        );
      }
    }
  ]
});
const editingData: Ref<Api.SystemManage.TaskInfo | null> = ref(null);
const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);
async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);
  const { error } = await fetchDeleteTask(checkedRowKeys.value);
  if (!error) {
    window.$message?.success('操作成功');
  }
}

function handleEdit(item: Api.SystemManage.TaskInfo) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openModal();
}
function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;

  openModal();
}
// 修改状态
async function handleStatusChange(data: Api.SystemManage.TaskInfo) {
  // request
  const { error } = await fetchUpdateTaskStatus({ id: data.id, isActive: !data.isActive });
  if (error) return;
  getDataByPage();
}
const operateType = ref<OperateType>('add');
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="任务列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation v-model:columns="columnChecks" :loading="loading" @refresh="getData">
          <template #prefix>
            <NButton size="small" ghost type="primary" @click="handleAdd">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
              {{ $t('common.add') }}
            </NButton>
            <NPopconfirm @positive-click="handleBatchDelete">
              <template #trigger>
                <NButton size="small" ghost type="error" :disabled="checkedRowKeys.length === 0">
                  <template #icon>
                    <icon-ic-round-delete class="text-icon" />
                  </template>
                  {{ $t('common.batchDelete') }}
                </NButton>
              </template>
              {{ $t('common.confirmDelete') }}
            </NPopconfirm>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <TaskOperateDrawer
        v-model:visible="visible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
